<template>
	<view :id="templateId" class="container tabbar-page">
		<template>
			<view
				class="navbar-wrap"
				:style="{ position: headerPosition, top: headerTop }"
			>
				<!-- 搜索区域 begin -->
				<view
					:style="themeStyles.backgroundMainColor"
					class="theme__search-wrap mp-search"
				>
					<view class="df df-r mp-search__wrap">
						<view
							@click="toggleCateMask('show')"
							class="df df-c type-icon-box"
						>
							<uni-icon
								name="category"
								size="48rpx"
								color="#ffffff"
							>
							</uni-icon>
							<text class="type-icon-text">分类</text>
						</view>
						<view class="df mp-search-box">
							<uni-icon
								name="search"
								size="48rpx"
								color="#999999"
							>
							</uni-icon>
							<input
								@confirm="searchGoods"
								@input="searchInput"
								@focus="showInputFocus()"
								@blur="hideInputFocus()"
								:focus="focus"
								class="search-input"
								type="text"
								v-model="searchValue"
								placeholder="搜索商品"
							/>
							<view
								v-if="showSearchBtn"
								@click.stop="searchGoods"
								class="df jc-c ai-c search-btn"
								>搜索</view
							>
						</view>
					</view>
				</view>

				<!-- 搜索区域 end -->

				<!-- 排序按钮区域 begin -->
				<view class="sort-bar">
					<!-- 主题色 -->

					<view
						v-for="(item, index) in sortBarList"
						:key="index"
						class="sort-bar__item"
						:style="{
							color:
								sortItem === item.sortType &&
								themeStyles.lightMainColor
						}"
						@click="tabClick(item.sortType)"
					>
						<text>{{ item.sortName }}</text>
						<view v-if="item.hasSort" class="p-box">
							<!-- 主题色 -->
							<text
								:style="{
									color:
										priceOrder === 1 &&
										sortItem === item.sortType &&
										themeStyles.lightMainColor
								}"
								class="fyicon icon-up"
							></text>
							<!-- 主题色 -->
							<text
								:style="{
									color:
										priceOrder === 2 &&
										sortItem === item.sortType &&
										themeStyles.lightMainColor
								}"
								class="fyicon icon-up down"
							></text>
						</view>
					</view>
				</view>
			</view>
			<!-- 排序按钮区域 end -->

			<!-- 商品区域 begin -->
			<view class="goods">
				<!-- 推荐商品 begin -->
				<view
					v-if="loadingType !== 'loading' && noCutGoods"
					class="no-data-wrap"
				>
					<empty
						:src="
							baseTemplateFileUri + 'image/emptyStatus/common.png'
						"
						size="small"
						desc="没有找到相关商品 ~"
					></empty>

					<view v-if="goodsList.length" class="trick-title">
						<trick-title
							title="为您推荐"
							iconName="love"
							:color="themeStyles.lightMainColor"
							:iconColor="themeStyles.lightMainColor"
						>
						</trick-title>
					</view>
				</view>
				<!-- 推荐商品 end -->

				<!-- 当前商品 begin -->
				<view class="goods-wrap">
					<uni-goods-list :goodsList="goodsList"> </uni-goods-list>
				</view>
				<uni-load-more
					v-if="goodsList.length"
					:status="loadingType"
				></uni-load-more>
				<!-- 当前商品 end -->
			</view>
			<!-- 商品区域 end -->

			<!-- 分类列表 -->
			<view
				class="cate-mask"
				:class="
					cateMaskState === 0
						? 'none'
						: cateMaskState === 1
						? 'show'
						: ''
				"
				@click="toggleCateMask"
			>
				<view
					class="cate-content"
					@click.stop.prevent="stopPrevent"
					@touchmove.stop.prevent="stopPrevent"
				>
					<scroll-view
						@scrolltolower="getMoreCate"
						scroll-y
						class="cate-list"
					>
						<view
							v-for="(item, index) in cateList"
							:key="index"
							class="cate-item"
							:class="{ active: item.goodsTypeId == goodsTypeId }"
							:style="{
								color:
									item.goodsTypeId == goodsTypeId &&
									themeStyles.mainColor,
								'border-color':
									item.goodsTypeId == goodsTypeId &&
									themeStyles.mainColor
							}"
							@click="changeCate(item)"
						>
							{{ item.goodsTypeName }}
						</view>
					</scroll-view>
				</view>
			</view>
		</template>

		<uni-tabbar
			@onClick="switchTabbar"
			:animationData="animationData"
			:badgeBg="themeStyles.lightMainColor"
			:tintColor="themeStyles.mainColor"
			color="#999999"
		>
		</uni-tabbar>
	</view>
</template>

<script>
const app = getApp();
/** api start */
import { queryGoodsList } from "@/lib/api/goodsServer/goods";
import { queryGoodsTypeList } from "@/lib/api/goodsServer/goodsType";
/** api end */
import { baseFileUri } from "@/utils/request/baseConfig";

/** commponents begin */
import uniTabbar from "@/components/uniTabbar";
import uniLoadMore from "@/components/uniLoadMore/uniLoadMore";
import uniGoodsList from "@/components/goods/uniGoodsList";
import uniIcon from "@/components/uniIcon/uniIcon";
import trickTitle from "@/components/trickTitle/trickTitle";
import empty from "@/components/empty";
/** commponents end */

/** mixins beagin */
import goodsMixin from "@/mixins/goods/goods";
import tabbarMixin from "@/mixins/tabbar";
/** mixins end */

/** 不参与页面渲染参数 begin */
// let currentPage = 1;
// let cateCurrentPage = 1;

let [currentPage, cateCurrentPage] = [1, 1];
const searchData = {
	searched: false,
	oldSearchValue: ""
};
/** 不参与页面渲染参数 end */

export default {
	mixins: [goodsMixin, tabbarMixin],
	components: {
		uniTabbar,
		empty,
		trickTitle,
		uniLoadMore,
		// uniGoodsCol,
		uniGoodsList,
		uniIcon
	},

	data() {
		return {
			sortBarList: [
				{
					sortName: "综合",
					sortType: null,
					hasSort: false
				},
				{
					sortName: "销量",
					sortType: "404720",
					hasSort: false
				},
				{
					sortName: "新品",
					sortType: "404730",
					hasSort: false
				},
				{
					sortName: "价格",
					sortType: "404710",
					hasSort: true
				}
			],
			goodsSort: "",
			focus: false,
			showSearchBtn: false,
			baseFileUri,
			goodsTypeId: "", //已选分类id
			sortType: "40", // 30:升 40: 降(true)序
			sortItem: null, // 排序规则 404730: 时间, 404720: 销量, null: 随机，404710: 价格
			searchValue: "",
			flist: [],
			cateMaskState: 0, //分类面板展开状态
			headerPosition: "fixed",
			headerTop: "0px",
			loadingType: "more", //加载更多状态
			priceOrder: 0, //1 价格从低到高 2价格从高到低
			cateList: [],
			cateLoadingType: "more",
			noCutGoods: false
		};
	},

	onLoad() {
		currentPage = 1;
		cateCurrentPage = 1;
		this.getGoodsList();
	},

	onShow() {
		// Object.assign(this.$data, this.$options.data());
		// this.focus = false;
		this.focusInput();
		this.taggerSearchBtn();
	},

	onHide() {
		this.focus = app.globalData.searchValue = false;
	},

	onPageScroll(e) {
		//兼容iOS端下拉时顶部漂移
		if (e.scrollTop >= 0) {
			this.headerPosition = "fixed";
		} else {
			this.headerPosition = "absolute";
		}
	},

	//下拉刷新
	async onPullDownRefresh() {
		Object.assign(this.$data, this.$options.data());
		this.focus = app.globalData.searchValue = false;
		currentPage = 1;
		cateCurrentPage = 1;
		await this.getGoodsList();
		uni.stopPullDownRefresh();
	},

	//加载更多
	onReachBottom() {
		if (this.loadingType === "more") {
			currentPage++;
			if (this.noCutGoods) {
				this.getChoiceList();
			} else {
				this.getGoodsList();
			}
		}
	},

	onShareAppMessage(res) {
		return {
			title: "我发现一个好商品，一起来看看吧！",
			path: "/pages/tabbar/index"
		};
	},

	methods: {
		/** 搜索框 begin */
		searchInput() {
			searchData.searched =
				searchData.oldSearchValue === this.searchValue;
		},

		showInputFocus() {
			this.focus = true;
			this.showSearchBtn = true;
		},

		hideInputFocus() {
			if (!this.searchValue) {
				setTimeout(() => {
					this.showSearchBtn = false;
				}, 100);
			}
		},

		focusInput() {
			if (this.loaded && app.globalData.searchValue) {
				this.focus = true;
			}
		},

		// 显示/ 隐藏 搜索按钮
		taggerSearchBtn() {
			if (!this.loaded) return;
			this.showSearchBtn =
				(!this.searchValue && app.globalData.searchValue) ||
				(this.searchValue && !searchData.searched);
		},

		// 搜索商品
		searchGoods(e) {
			currentPage = 1;
			this.focus = false;
			this.showSearchBtn = false;
			app.globalData.searchValue = false;
			searchData.oldSearchValue = this.searchValue;
			this.getGoodsList();
		},
		/** 搜索框 end */

		// 加载更多分类
		getMoreCate() {
			console.log("cateLoadingType", this.cateLoadingType);
			if (this.cateLoadingType === "more") {
				cateCurrentPage++;
				this.getCateList();
			}
		},

		// 获取分类列表
		async getCateList() {
			const propsData = {
				currentPage: cateCurrentPage,
				pageSize: 20
			};
			try {
				const res = await queryGoodsTypeList(propsData);

				if (propsData.currentPage === 1) {
					this.cateList = res.data.list;
					this.cateList.unshift({
						goodsTypeName: "全部",
						goodsTypeId: ""
					});
				} else {
					this.cateList = this.cateList.concat(res.data.list);
				}
				const noMore = this.cateList.length >= res.data.total;
				this.cateLoadingType = noMore ? "noMore" : "more";
			} catch (error) {
				console.log("error", error);
				this.$api.showToast(error.resultInfo || "出错了 * _ *");
			}
		},

		// 获取推荐商品
		async getChoiceList() {
			this.loadingType = "loading";
			const propsData = {
				currentPage
			};
			try {
				await this.getGoodsListAll(propsData);
				this.loaded = true;

				this.focusInput();
				searchData.searched = true;
				this.taggerSearchBtn();
				app.globalData.searchValue = false;
			} catch (error) {
				console.log("error", error);
			}
		},

		// 获取商品列表
		async getGoodsList() {
			this.loadingType = "loading";
			const propsData = {
				currentPage,
				goodsName: this.searchValue || "",
				goodsTypeId: this.goodsTypeId || "",
				sortItem: this.sortItem,
				sortType: this.sortType,
				hideLoading: false
			};

			try {
				await this.getGoodsListAll(propsData);
				if (currentPage === 1 && !this.goodsList.length) {
					this.noCutGoods = true;
					this.loaded = true;
					await this.getChoiceList();
				} else {
					this.loaded = true;
					this.noCutGoods = false;
					uni.hideLoading();
					this.focusInput();
					searchData.searched = true;
					this.taggerSearchBtn();
					app.globalData.searchValue = false;
				}
			} catch (error) {
				console.log("error", error);
				uni.hideLoading();
				this.$api.showToast(error.resultInfo || "出错了 * _ *");
			}
		},
		/** jlzm end */

		//筛选点击
		tabClick(index) {
			currentPage = 1;
			this.orderFlag = index === 0 ? null : index;
			if (this.sortItem === index && index !== "404710") {
				return;
			}
			this.sortItem = index;
			if (index === "404710") {
				this.priceOrder = this.priceOrder === 1 ? 2 : 1;
				this.sortType = this.sortType === "40" ? "30" : "40";
			} else {
				this.sortType = "40";
				this.priceOrder = 0;
			}

			uni.pageScrollTo({
				duration: 300,
				scrollTop: 0
			});
			this.getGoodsList();
		},

		//显示分类面板
		toggleCateMask(type) {
			let timer = type === "show" ? 10 : 300;
			let state = type === "show" ? 1 : 0;
			this.cateMaskState = 2;
			if (type === "show") {
				!this.cateList.length && this.getCateList();
			}
			setTimeout(() => {
				this.cateMaskState = state;
			}, timer);
		},

		//分类点击
		changeCate(item) {
			this.goodsTypeId = item.goodsTypeId;
			this.toggleCateMask();
			uni.pageScrollTo({
				duration: 300,
				scrollTop: 0
			});
			currentPage = 1;
			this.getGoodsList();
		},

		//详情
		navToDetailPage(item) {
			const goodsId = item.goodsId;
			uni.navigateTo({
				url: `/pages/goods/goodsDetail?goodsId=${goodsId}`
			});
		},

		stopPrevent() {}
	}
};
</script>

<style lang="scss">
@import "@/pages/tabbar/styles/category.scss";
</style>
